// import { useCallback, useEffect } from 'react';
import BackPage from '@/components/BackPage';
import SaleBadge from '@/components/SaleBadge';
import SelectOne from '@/components/SelectOne';
import { getStockList } from '@/services/stock';
import { getQueryParams } from '@/utils/utils';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Popover } from 'antd';
import moment from 'moment';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import CreateNew from './components/CreateNew';
import styles from './index.less';

const GoodsRecord: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const qs = getQueryParams();
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectList, setSelectList] = useState<any[]>([]);
  const [createNew, setCreateNew] = useState<boolean>(false);
  let nowDate = Date.parse(new Date().toString());

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      const res = await getStockList({ pageIndex: currentPage, saleid: qs.id });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage, qs.id]);

  useEffect(() => {
    getList();
  }, [getList]);

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '商品编号',
      dataIndex: 'goodsid',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '商品名称',
      dataIndex: 'goodsname',
      ellipsis: true,
    },
    {
      title: '批次',
      dataIndex: 'flot',
      ellipsis: true,
    },
    {
      disable: true,
      title: '状态',
      dataIndex: 'expireState',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        all: { text: '超长'.repeat(50) },
        '2': {
          text: '已过期',
          status: 'Error',
        },
        '1': {
          text: '临期',
          status: 'Error',
        },
        '0': {
          text: '日期正常',
          status: 'Success',
          disabled: true,
        },
      },
    },
    {
      title: '新增数量',
      dataIndex: 'qty',
    },
    {
      title: '入库时间',
      key: 'timeadd',
      render: (text, record) => [
        <Popover
          content={
            <div>
              <p>生产日期：{`${moment(Number(record.pdate)).format('YYYY-MM-DD HH:mm:ss')}`}</p>
              <p>有效期至：{`${moment(Number(record.exdate)).format('YYYY-MM-DD HH:mm:ss')}`}</p>
              {(record.exdate - nowDate) / 1000 / 60 / 60 / 24 > 0 ? (
                <p>{`还有${((record.exdate - nowDate) / 1000 / 60 / 60 / 24).toFixed(0)}天过期`}</p>
              ) : (
                <p>已过期</p>
              )}
            </div>
          }
          key={record.id}
          title=""
        >
          <div style={{ cursor: 'pointer' }}>{`${moment(Number(record.timeadd)).format(
            'YYYY-MM-DD HH:mm:ss',
          )}`}</div>
        </Popover>,
      ],
    },
  ];

  return (
    <BackPage thisRoute={'/goodsRecord'} lastRoute={'入库记录'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'商品编号'}
          fromWhere={'goodsRecord'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          dataSource={selectList.length !== 0 ? selectList : list}
          actionRef={actionRef}
          cardBordered={false}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime],
                };
              }
              return values;
            },
          }}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
        />
        <Button
          className={styles.newbtn}
          onClick={() => {
            setCreateNew(true);
          }}
        >
          新建入库单
        </Button>
        <CreateNew
          visible={createNew}
          handleCancel={() => {
            setCreateNew(false);
          }}
          getList={getList}
        />
        <SaleBadge />
      </div>
    </BackPage>
  );
};
export default GoodsRecord;
